package com.ldxiwxr.controller.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.ldxiwxr.common.common.Result;
import com.ldxiwxr.common.config.AliOSSConfig;
import com.ldxiwxr.common.utils.UUIDUtils;
import com.ldxiwxr.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * 文件上传下载控制器
 * @author SuBanxia
 */
@Api(tags = "/fileController")
@RestController
@RequestMapping("/file")
public class fileController {

    @Autowired
    private IUserService userService;

    @Resource
    private AliOSSConfig aliOSSConfig;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<?> upload(@RequestParam("Avatar1") MultipartFile file) throws IOException {

        //获取文件名称及其后缀
        String objectName = file.getOriginalFilename();
        String substring = objectName.substring(objectName.lastIndexOf("."));
        //拼接最终文件名
        String finalFileName = UUIDUtils.getUUID() + substring;
        //修改用户文件名
        userService.updateUserAvatar(finalFileName);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOSSConfig.getEndpoint(), aliOSSConfig.getAccessKeyId(), aliOSSConfig.getAccessKeySecret());
        try {
            //上传文件
            ossClient.putObject(aliOSSConfig.getBucket(), finalFileName, new ByteArrayInputStream(file.getBytes()));
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } finally {
            if (ossClient != null) {
                //关闭客户端
                ossClient.shutdown();
            }
        }
        return Result.success("图片上传成功");
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{objectName}")
    public void download(@PathVariable String objectName, HttpServletResponse response) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOSSConfig.getEndpoint(), aliOSSConfig.getAccessKeyId(), aliOSSConfig.getAccessKeySecret());
        try {
            // 设置URL过期时间为minutes分钟（防盗链的处理）。
            Date expiration = new Date(new Date().getTime() + 60 * 1000);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(aliOSSConfig.getBucket(), objectName, expiration);
            response.setContentType("application/octet-stream");
            response.sendRedirect(url.toString());
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
